package cn.com.gridinfo.sooc.core.my.personal.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jeremy.arad.Arad;
import com.jeremy.arad.support.picasso.CircleTransform;
import com.jeremy.arad.utils.AnimUtil;
import com.jeremy.arad.utils.Log;
import com.jeremy.arad.utils.StringUtils;
import com.squareup.picasso.Picasso;

import java.io.File;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import cn.com.gridinfo.sooc.R;
import cn.com.gridinfo.sooc.base.BaseSoocActivity;
import cn.com.gridinfo.sooc.common.LocalMark;
import cn.com.gridinfo.sooc.core.my.commen.CodeConst;
import cn.com.gridinfo.sooc.core.my.dao.MyDao;
import cn.com.gridinfo.sooc.utils.CompressBitmap;
import cn.com.gridinfo.sooc.utils.DateUtil;
import cn.com.gridinfo.sooc.utils.MessageUtils;

/**
 * 个人信息
 * Created by 刘晓晨 on 2015/12/11.
 */
public class PersonalActivity extends BaseSoocActivity {
    @InjectView(R.id.headimg)
    ImageView headImg;//头像
    @InjectView(R.id.headimg_rl)
    RelativeLayout headimgRl;//点击更换头像
    @InjectView(R.id.nickName)
    TextView nickName;//昵称
    @InjectView(R.id.phoneNumber)
    TextView phoneNumber;//手机号
    @InjectView(R.id.email)
    TextView email;//邮箱
    MyDao myDao;// 用户dao
    private PopupWindow popupWindow;
    private int popupWindowType;
    String headFileName = "soocHead.jpg";//头像名称;
    String headFileDir;//头像目录
    private static final int CHANGECELLNUMBER = 1;// 修绑定手机号
    private static final int CHANGENICKNAME = 2;// 修改昵称
    private static final int PHOTO_REQUEST_TAKEPHOTO = 3;// 拍照
    private static final int PHOTO_REQUEST_GALLERY = 4;// 从相册中选择
    private static final int PHOTO_REQUEST_CUT = 5;// 结果
    private int crop = 189;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_personal);
        ButterKnife.inject(this);
        myDao = new MyDao(this);
        //点击头像，弹出PopupWindow
        headimgRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindowType = 0;
                getPopupWindow();
                popupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
            }
        });
        initView();//请求用户信息
    }

    //初始化界面数据
    private void initView() {
        myDao.myMainView();
    }

    //请求成功返回数据
    @Override
    public void onRequestSuccess(int requestCode) {
        super.onRequestSuccess(requestCode);
        if (myDao.status.equals("0")) {
            switch (requestCode) {
                case CodeConst.GET_MYINFO:
                    //显示用户信息
                    showMyInfo();
                    break;
                case CodeConst.UPDATEHEADIMG:
                    //更新用户头像
                    String imgUrl = Arad.preferences.getString("newPic");
                    if (imgUrl != null && !imgUrl.equals("")) {
                        Arad.imageLoader.load(imgUrl).skipMemoryCache().
                                transform(new CircleTransform()).placeholder(R.mipmap.my_headimg)
                                .error(R.mipmap.my_headimg).into(headImg);
                        MessageUtils.showRightImageShortToast(this, "更新头像成功！");
                    } else {
                        headImg.setImageResource(R.mipmap.ic_launcher);
                    }
                    setResult(RESULT_OK);
                    break;
            }
        }
    }

    //拿到信息，显示
    private void showMyInfo() {
        if (!StringUtils.isNull(myDao.userInfo.getImg()) && myDao.userInfo.getImg().contains("http")) {
            Picasso.with(this).load(myDao.userInfo.getImg()).transform(new CircleTransform()).
                    error(R.mipmap.my_headimg).placeholder(R.mipmap.my_headimg).into(headImg);//加载头像
        } else {
            headImg.setImageResource(R.mipmap.my_headimg);
        }
        nickName.setText(myDao.userInfo.getUsername());// 加载昵称
        if (StringUtils.isNull(myDao.userInfo.getCellphone())) {
            //加载手机号码，如未绑定显示未绑定
            phoneNumber.setText("未绑定");
            phoneNumber.setTextColor(Color.LTGRAY);
        } else {
            phoneNumber.setText(myDao.userInfo.getCellphone());
        }
        if (StringUtils.isNull(myDao.userInfo.getEmail())) {
            //加载邮箱地址，如未绑定显示未绑定
            email.setText("未绑定");
            email.setTextColor(Color.LTGRAY);
        } else {
            email.setText(myDao.userInfo.getEmail());
        }
//        if (myDao.userInfo.getIdentityType().equals("5")) {
//            // 游客身份，不显示性别一栏
//            sexRl.setVisibility(View.GONE);
//        } else {// 显示性别  1：男  其余：女
//            sexRl.setVisibility(View.VISIBLE);
//            if (myDao.userInfo.getSex() == 1) {
//                sex.setText("男");
//            } else {
//                sex.setText("女");
//            }
//        }
        Arad.preferences.putString(LocalMark.USER_HEADIMG.getName(), myDao.userInfo.getImg());
        Arad.preferences.putString(LocalMark.USER_TEL.getName(), myDao.userInfo.getCellphone());
        Arad.preferences.putString(LocalMark.USER_EMAIL.getName(), myDao.userInfo.getEmail());
        Arad.preferences.putInteger(LocalMark.USER_SEX.getName(), myDao.userInfo.getSex());
        Arad.preferences.flush();
    }

    //获取popWindow实例
    private void getPopupWindow() {
        if (null != popupWindow) {
            popupWindow.dismiss();
            WindowManager.LayoutParams lp = getWindow().getAttributes();
//            lp.alpha = 1.0f;
            getWindow().setAttributes(lp);
        } else if (popupWindowType == 0) {
            //弹出更换头像的popupWindow
            WindowManager.LayoutParams lp = getWindow().getAttributes();
//            lp.alpha = 0.3f;
            getWindow().setAttributes(lp);
            initPopupWindow();
        }
    }

    //设置标题
    @Override
    public String setupToolBarTitle() {
        return "个人信息";
    }

    //设置左边按钮
    @Override
    public boolean setupToolBarLeftButton(ImageView leftButton) {
        return true;
    }

    //返回
    @OnClick(R.id.toolbar_leftbtn)
    void onGoBack() {
        finish();
    }

    //点击修改昵称
    @OnClick(R.id.nickName_rl)
    void changeNickname() {
        Intent intent = new Intent(this, ChangeNicknameActivity.class);
        intent.putExtra("nickname", nickName.getText().toString().trim());//将昵称传出
        startActivityForResult(intent, CHANGENICKNAME);
        AnimUtil.intentSlidIn(this);
    }

    //点击绑定手机号
    @OnClick(R.id.phoneNumber_rl)
    void changePnumber() {
        if (phoneNumber.getText().toString().trim().equals("未绑定")) {
            if (StringUtils.isNull(myDao.userInfo.getCellphone())) {
                //用户没有绑定手机号的时候
                Intent intent = new Intent(this, ChangeCellNumberActivity.class);
                intent.putExtra("noBoundCellPhone", "yes");//传入下一个界面
                startActivity(intent);
                AnimUtil.intentSlidIn(this);
            } else {
                //绑定了手机号，先跳转到已经绑定的手机号
                Intent intent = new Intent(this, OnBoundCellNumberActivity.class);
                intent.putExtra("cellphone", Arad.preferences.getString(LocalMark.USER_TEL.getName()));//将手机号传出
                startActivity(intent);
                AnimUtil.intentSlidIn(this);
            }
        } else {
            //绑定了手机号，先跳转到已经绑定的手机号
            Intent intent = new Intent(this, OnBoundCellNumberActivity.class);
            intent.putExtra("cellphone", Arad.preferences.getString(LocalMark.USER_TEL.getName()));//将手机号传出
            startActivity(intent);
            AnimUtil.intentSlidIn(this);
        }
    }

    //点击更换邮箱
    @OnClick(R.id.email_rl)
    void changeEmail() {
        Intent intent = new Intent(this, ChangeEmailActivity.class);
        if (StringUtils.isNull(myDao.userInfo.getEmail())) {
            //没有绑定邮箱，直接跳转到绑定邮箱界面
            Intent intent1 = new Intent(this, ChangeEmailActivity.class);
            intent1.putExtra("noBoundEmail", "yes");//传入下一个界面，用于设置title
            startActivityForResult(intent1, CHANGECELLNUMBER);
            AnimUtil.intentSlidIn(this);
        } else {
            //绑定邮箱，跳转到已绑定邮箱界面
            Intent newIntent = new Intent(this, OnBoundEmailActivity.class);
            newIntent.putExtra("emailAddress", Arad.preferences.getString(LocalMark.USER_EMAIL.getName()));//将邮箱地址传出
            startActivity(newIntent);
            AnimUtil.intentSlidIn(this);
        }
    }

    //创建更换头像popupWindow
    private void initPopupWindow() {
        File fileDir = new File(Environment.getExternalStorageDirectory() + "/sooc/tmpHead/");
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        headFileDir = fileDir.getAbsolutePath();
        //获取 自定义布局文件activity_popupWindow.xml视图
        View popupWindow_view = getLayoutInflater().inflate
                (R.layout.my_personal_headimg_popupwindow, null, false);
        popupWindow = new PopupWindow
                (popupWindow_view, WindowManager.LayoutParams.MATCH_PARENT,
                        findViewById(android.R.id.content).getHeight(), true);
        // 弹出popupWindow后背景变暗

        TextView takePhoto;//实例化
        takePhoto = (TextView) popupWindow_view.findViewById(R.id.takePhono);//绑定 “拍照”
        // 点击拍照
        takePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String tempPath = headFileDir + "/" + headFileName;
                String status = Environment.getExternalStorageState();
                if (status.equals(Environment.MEDIA_MOUNTED)) {
                    //判断是否有SD卡
                    Intent intent = new Intent(
                            MediaStore.ACTION_IMAGE_CAPTURE);
                    //下面这句指定调用相机拍照后的照片存储的路径
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri
                            .fromFile(new File(tempPath)));
                    startActivityForResult(intent, PHOTO_REQUEST_TAKEPHOTO);
                } else {
                    MessageUtils.showImageShortToast(getApplicationContext(), "没有SD卡");
                }
                popupWindow.dismiss();
            }
        });
        TextView mobilePhoto;
        mobilePhoto = (TextView) popupWindow_view.findViewById(R.id.mobilePhoto);// 绑定“手机相册选择”
        //点击本地相册
        mobilePhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_PICK, null);
                intent.setDataAndType(
                        MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                        "image/*");
                startActivityForResult(intent, PHOTO_REQUEST_GALLERY);

                popupWindow.dismiss();
            }
        });
        TextView cancel;
        cancel = (TextView) popupWindow_view.findViewById(R.id.cancel);// 绑定“取消”
        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();//背景置为灰色半透明
                WindowManager.LayoutParams lp = getWindow().getAttributes();
//                lp.alpha = 1.0f;
                getWindow().setAttributes(lp);
            }
        });
        //点击其他地方消失
        popupWindow_view.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();//popupWindow消失
                    WindowManager.LayoutParams lp = getWindow().getAttributes();
//                    lp.alpha = 1.0f;
                    getWindow().setAttributes(lp);
                    popupWindow = null;
                }
                return false;
            }
        });
    }

    //修改头像，数据回填
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        Log.d("resultCode=" + resultCode);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case PHOTO_REQUEST_TAKEPHOTO://拍照保存成功后调用
                    File tempPath = new File(headFileDir + "/" + headFileName);
                    startPhotoZoom(Uri.fromFile(tempPath));
                    break;
                case PHOTO_REQUEST_GALLERY://选择本地图片时
                    Uri uri = null;
                    //做非空判断，当我们觉得不满意想重新剪裁的时候便不会报异常，下同
                    if (data != null) {
                        uri = data.getData();
                        startPhotoZoom(uri);
                    } else {
                        popupWindow.dismiss();//popupWindow消失

                    }
                    break;
                case PHOTO_REQUEST_CUT://返回的结果
                    if (data != null) {
                        setPicToView(data);

                    }

                    break;
                case CHANGENICKNAME://修改昵称
                    nickName.setText(Arad.preferences.getString(LocalMark.USER_NICKNAME.getName().toString()));//更新下昵称
                    setResult(RESULT_OK);
                    break;
                case CHANGECELLNUMBER:
                    //从修改手机号码页面返回
                    phoneNumber.setText(Arad.preferences.getString(LocalMark.USER_TEL.getName()));
                    phoneNumber.setTextColor(getResources().getColor(R.color.color_tv333));
                    break;
                default:
                    break;
            }

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    //更新显示
    @Override
    protected void onRestart() {
        super.onRestart();
        if (!StringUtils.isNull(Arad.preferences.getString(LocalMark.USER_TEL.getName()))) {
            //手机号
            phoneNumber.setText(Arad.preferences.getString(LocalMark.USER_TEL.getName()));
            phoneNumber.setTextColor(getResources().getColor(R.color.color_tv333));
        }
        if (!StringUtils.isNull(Arad.preferences.getString(LocalMark.USER_EMAIL.getName()))) {
            //邮箱
            email.setText(Arad.preferences.getString(LocalMark.USER_EMAIL.getName()));
            email.setTextColor(getResources().getColor(R.color.color_tv333));
        }
    }

    //裁剪
    private void startPhotoZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        //下面这个crop=true是设置在开启的Intent中设置显示的VIEW可裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, PHOTO_REQUEST_CUT);

    }

    /**
     * 保存裁剪之后的图片数据 并上传
     *
     * @param picdata
     */
    private void setPicToView(Intent picdata) {
        Bundle extras = picdata.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            File file = CompressBitmap.saveBitmap(photo, DateUtil.getCurrDateStamp() + ".jpg");
//            上传图片
            myDao.uploadPic(file);
        }
    }

}
